
<template>
<div v-loading="loading">

  <div class="btns">
    <el-button v-if="verifyRoleType.iskycgly() " type="primary" @click="openDialog"><el-icon class="mr-[5px]"><Plus /></el-icon>新增</el-button>
    <el-button @click="handleDeleteS"><el-icon class="mr-[5px]"><DeleteFilled /></el-icon>删除</el-button>
    <el-button @click="download" v-if="verifyRoleType.iskycgly()" ><svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出</el-button>
    <!--          <el-button type="primary" icon="Histogram" > 统计分析</el-button>-->
  </div>
  <div>
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
    >
      <el-table-column
          type="selection"
          width="55"
          :selectable="isRowSelectable"
      ></el-table-column>
      <el-table-column label="项目名称" sortable="p.name">
        <template #default="scope">
          <span @click="openDetails(scope.row , 'name')" class="clickable-status" >{{ scope.row.projectName }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="chargerName"
          label="负责人"
          sortable="p.charger_name"
      ></el-table-column>
      <el-table-column
          prop="projectTypeName"
          label="项目分类"
          sortable="p.project_type"
      ></el-table-column>
      <el-table-column
          prop="alterdate"
          label="变更时间"
          sortable="b.alterdate"
      ></el-table-column>
      <el-table-column
          prop="unitName"
          label="所属单位"
          sortable="p.unit_id"
      ></el-table-column>
      <el-table-column  sortable="b.checkstatus" prop="checkstatus" label="审核状态">
        <template #default="{ row }">
          <CommonLabel
              :dataList="checkStatusList"
              valueKey="dictValue"
              labelKey="dictLabel"
              :value="row.checkstatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
           <!-- 科研人员操作-->
          <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" size="small" plain @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 2" @click="openDetails(scope.row)" plain type="primary" size="small">
            查看
          </el-button>
          <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 1" plain type="warning" size="small" @click="handleCancel(scope.row)">
            撤销
          </el-button>

          <!-- 科研秘书操作 -->
          <el-button v-if="verifyRoleType.isKyms() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-if="verifyRoleType.isKyms() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" size="small" plain @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 1" plain type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 1 && scope.row.isAuditor" plain type="success" size="small" @click="openDetails(scope.row , 'name')">
            审核
          </el-button>
          <el-button v-if="verifyRoleType.isKyms() && scope.row.checkstatus == 2" @click="openDetails(scope.row)" plain type="primary" size="small">
            查看
          </el-button>

          <!-- 科研管理员操作 -->
          <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" plain type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" @click="openDetails(scope.row)" plain type="primary" size="small">
            查看
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)" type="danger" size="small" plain @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1" plain type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1" @click="openDetails(scope.row)" plain type="primary" size="small">
            查看
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1 && scope.row.isAuditor" plain type="success" size="small" @click="openDetails(scope.row, 'name')">
            审核
          </el-button>
          <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 2" @click="openDetails(scope.row)" plain type="primary" size="small">
            查看
          </el-button>


<!--          <el-button  @click="woshizujian('7bcbfe53693141e9b9ef1030e6681944')">我是组件</el-button>-->
<!--          <el-button  @click="openauditBtn(scope.row)" plain type="primary" size="small">cs审核</el-button>-->
<!--          <el-button  v-if="!(verifyRoleType.isKymsOrkycgly() && scope.row.checkstatus == 2)" plain type="primary"  size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
<!--          <el-button  v-if="verifyRoleType.isKyry() && scope.row.checkstatus == '1'" plain type="warning" size="small" @click="handleCancel(scope.row)">撤销</el-button>-->
<!--          <el-button v-if="scope.row.isAuditor"  plain type="success" size="small" @click="openDetails(scope.row)"  >审核</el-button>-->
<!--          <el-button  v-if="scope.row.checkstatus == -1 || scope.row.checkstatus == 3" type="danger" size="small"  plain  @click="handleDelete(scope.row)">删除</el-button>-->
<!--          <el-button v-if="scope.row.checkstatus ==2"  @click="openDetails(scope.row)"  plain type="primary" size="small" >查看</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <el-pagination
          layout="->,prev, pager, next, total"
          :total="count"
          currentPage1="10"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <addjfdzDiaiog
      ref="dialogRef"
      :visible="dialogVisible"
      @Getlist="getslist"

  ></addjfdzDiaiog>
  <compilejfdzDialog
      ref="opencompilejfdzDialog"
      @Getlist="getslist"
  >

  </compilejfdzDialog>
  <detailsjfdzDialog
      ref="opendetailsjfdzDialog"
      @success="getslist"
  >

  </detailsjfdzDialog>
  <audit
      ref="openaudit"

  >
  </audit>
  <jftzsqTable
      ref="jftzsqTables"
  >

  </jftzsqTable>
</div>
</template>

<script setup lang="ts">
const loading = ref(false) // 添加加载状态
import jftzsqTable from '@/components/money/jftzsqTable.vue'
import { verifyRoleType } from "@/utils/main";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useDictFetch from "@/hooks/useDictFetch";
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
import audit from  './../audit.vue'
import {onBeforeMount, ref} from "vue";
import {
  list,
  remove,
  exports
} from '@/api/money/jfdzApi'
import addjfdzDiaiog from './addjfdzDialog.vue'
import compilejfdzDialog from './compilejfdzDialog.vue'
import detailsjfdzDialog from './jfdzDetails.vue'
import {ElMessage, ElMessageBox} from "element-plus";
//测试组件
const jftzsqTables = ref(null)
const woshizujian = function (x) {
  jftzsqTables.value.openjftzsqTable(x)
}
const emit = defineEmits(['GetTitleCard'])


//导出
import {handleFileDownload} from '@/utils/downloadSz'
const download = function (){
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitld 从数组转换为字符串
  if (Array.isArray(requestData.unitld)) {
    requestData.unitld = requestData.unitld.join(',');//所属单位处理数组转字符串
    requestData.projectType = requestData.projectType.join(',');//项目分类
    requestData.Status = requestData.Status.join(',');//审核状态
  }
  exports({
    ...getListParme
  })
      .then((res)=>{
        if (!(res instanceof Blob)) {
          ElMessage({
            type: 'info',
            message: '响应数据不是 Blob 类型',
          })
        }else {
          handleFileDownload(res, '经费调账');
        }
      })
}


const openaudit = ref(null)
const openauditBtn = function (row){
  openaudit.value.openaudit(row)
}
// 控制弹窗显示与隐藏的变量
const dialogVisible = ref(false);


// 打开弹窗的方法
const dialogRef = ref(null);
const openDialog = () => {
  dialogRef.value.openDialog();
};

onBeforeMount(()=>{
  getslist()
})

const getListParme = defineModel();



//请求列表
const getslist = function () {
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitld 从数组转换为字符串
  if (Array.isArray(requestData.unitld)) {
    requestData.unitld = requestData.unitld.join(',');//所属单位处理数组转字符串
    requestData.projectType = requestData.projectType.join(',');//项目分类
    requestData.Status = requestData.Status.join(',');//审核状态
  }
  list({
    pageNum:1,
    pageSize:10,
    ...requestData
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows
    emit('GetTitleCard')
  })

}

//分页
const count = ref(0)
const handleCurrentChange = (val: number) => {
  console.log(`${val} items per page`)
}
// 处理排序变化的方法
// prop：表示当前进行排序的列对应的字段名
// order：表示当前的排序顺序，有三种可能的值：
// 'ascending'：代表正序排序。
// 'descending'：代表倒序排序。
// null：表示取消排序，在当前代码中暂未对该情况进行处理。
const handleSortChange = (row) => {
  getListParme.value.orderByColumn = row.column.sortable;
  getListParme.value.isAsc=row.order;
  getslist();
};

// 定义表格数据
const tableData = ref([
  // {
  //   alterdate: "2025-01-14",//变更时间
  //   chargerName: "老学生",//负责人
  //   checkstatus: "2",//审核状态 1保存 2 保存并通过
  //   id: "2c97a3549424ba1801946090087a0505",//
  //   projectId: "2c97a3549424ba18019425207dd5000c",// 项目id
  //   projectName: "基于CRISPR-Cas9技术的基因编辑在遗传性疾病治疗中的应用研究111444444",//项目名称
  //   projectTypeName: "一般项目",//项目分类
  //   unitName: "基础医学部",//所属单位
  // },
  // {
  //   projectName: '项目 A',
  //   personInCharge: '赵六',
  //   projectCategory: '技术研发',
  //   changeTime: '2025-03-01 10:00',
  //   affiliatedUnit: '科技公司 A',
  //   auditStatus: '已通过'
  // },
  // {
  //   projectName: '项目 B',
  //   personInCharge: '孙七',
  //   projectCategory: '市场推广',
  //   changeTime: '2025-03-02 14:30',
  //   affiliatedUnit: '营销公司 B',
  //   auditStatus: '待审核'
  // },
  // {
  //   projectName: '项目 C',
  //   personInCharge: '周八',
  //   projectCategory: '产品设计',
  //   changeTime: '2025-03-03 09:15',
  //   affiliatedUnit: '设计工作室 C',
  //   auditStatus: '未通过'
  // }
]);

// 存储选中的行数据
const selectedProjects = ref([]);

// 处理复选框选择变化的方法
const handleSelectionChange = (val) => {
  selectedProjects.value = val;
  console.log(val)

};
//批量删除
const handleDeleteS = () => {
  if(selectedProjects.value.length < 1){
    ElMessage({
      type: 'info',
      message: '请选择删除项',
    })
  }else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          const idString = selectedProjects.value.map(item => item.id).join(',');
          remove(idString)
              .then((res)=>{
                if(res.code == 200){
                  ElMessage({
                    type: 'success',
                    message: res.msg,
                  })
                  getslist()
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })


        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled',
          // })
        })

  }
}
const compileRow = ref({})
const opencompilejfdzDialog = ref(null);
//打开详情
const opendetailsjfdzDialog = ref(null)
const openDetails = (row ,name) => {
  // 这里可以添加实际的编辑逻辑，比如弹出编辑表单等
  compileRow.value = row;
  opendetailsjfdzDialog.value.opencompileDialog(row , name);
};
//撤销
import { cancelProcess } from "@/api/project/common";
//点击撤销
const handleCancel = async (row) => {
  loading.value = true // 开始加载
  try {
    const res = await cancelProcess(row.processInstanceId);
    if (res.data) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });

    } else {
      ElMessage({
        message: "操作失败！",
        type: "warning",
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false // 结束加载
  }
};
// 处理编辑操作
const handleEdit = (row) => {
  // 这里可以添加实际的编辑逻辑，比如弹出编辑表单等
  compileRow.value = row;
  opencompilejfdzDialog.value.opencompileDialog(row);
};

// 处理删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认！删除这条数据?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true // 开始加载
        remove(row.id)
            .then((res)=>{
              if(res.code == 200){
                ElMessage({
                  type: 'success',
                  message: res.msg,
                })
                getslist()
              }else {
                ElMessage({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .finally(() => {
              loading.value = false // 结束加载
            })

      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })

};

const drawer = ref(false) //更多在弹出
function cancelClick() {
  drawer.value = false
}

//时间区间选择
const optionsdata = [
  {
    value: 'daterange',
    label: '年/月/日',
  },
  {
    value: 'monthrange',
    label: '月',
  },
  {
    value: 'yearrange',
    label: '年',
  },

]

const year = ref<'daterange' | 'monthrange' | 'yearrange'>('daterange')

const valueDate = ref([])
//时间区间选择end
//判断复选框
const isRowSelectable = (row) => {
  return row.checkstatus!== '1' && row.checkstatus!== '2';
};
// 暴露 getList 方法供父组件调用
defineExpose({
  getslist,openaudit
});
</script>
<style scoped lang="scss">
.flex-input{
  display: flex;
  margin: 10px 5px 10px 0;
}
.flex-input > div{
  margin-right: 10px;
  width: 50%;
}
.data-flex{
  display: flex;
  margin: 0 3px;
  div:first-child{
    margin-right: 10px;
  }
}
.sss > div{
  margin: 5px 3px;
  width: 100%;
}
.zhi{
  margin: 0 10px;
}
.clickable-status{
  color:#23527c;
}
.clickable-status:hover{
  color:#23527c;
  cursor: pointer;
  text-decoration: underline;
}
.btns {
  margin-bottom: 20px;
}
</style>